package org.hbhk.hxl.gateway.route;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.StringTokenizer;

public class UrlUtil {

	// 对url中的参数进行url编码
	public static String getURLEncoder(String str) {
		try {
			int index = str.indexOf("?");
			if (index < 0)
				return str;
			String query = str.substring(0, index);
			String params = str.substring(index + 1);
			Map<String, String> map = getMapArgs(params);
			String encodeParams = transMapToString(map);
			return query + "?" + encodeParams;
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}
		return "";
	}

	// 将url参数格式转化为map
	public static Map<String, String> getMapArgs(String params) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		String[] pairs = params.split("&");
		for (int i = 0; i < pairs.length; i++) {
			int pos = pairs[i].indexOf("=");
			if (pos == -1)
				continue;
			String argname = pairs[i].substring(0, pos);
			String value = pairs[i].substring(pos + 1);
			value = URLEncoder.encode(value, "utf-8");
			map.put(argname, value);
		}
		return map;
	}

	// 将map转化为指定的String类型
	public static String transMapToString(Map<String, String> map) {
		java.util.Map.Entry<String, String> entry;
		StringBuffer sb = new StringBuffer();
		for (Iterator<Entry<String, String>> iterator = map.entrySet().iterator(); iterator.hasNext();) {
			entry = (java.util.Map.Entry<String, String>) iterator.next();
			sb.append(entry.getKey().toString()).append("=")
					.append(null == entry.getValue() ? "" : entry.getValue().toString())
					.append(iterator.hasNext() ? "&" : "");
		}
		return sb.toString();
	}
	

	// 将String类型按一定规则转换为Map
	public static Map<String, String> TransStringToMap(String mapString) {
		Map<String, String> map = new HashMap<String, String>();
		java.util.StringTokenizer items;
		for (StringTokenizer entrys = new StringTokenizer(mapString, "&"); entrys.hasMoreTokens(); map
				.put(items.nextToken(), items.hasMoreTokens() ? ((String) (items.nextToken())) : null))
			items = new StringTokenizer(entrys.nextToken(), "=");
		return map;
	}

}
